package com.googlecode.elidom.common.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ServiceController {

	@RequestMapping(value = "/*/service/*.def", headers = "Accept=application/json;charset=UTF-8")
	public @ResponseBody
	String invokeDef(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return "{\"invokeDef\":\"ok\"}";
	}

	@RequestMapping(value = "/*/service/*.json", headers = "Accept=application/json;charset=UTF-8")
	public @ResponseBody
	String invokeJson(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return "{\"invokeJson\":\"ok\"}";
	}

	@RequestMapping(value = "/*/service/*.jsonp", headers = "Accept=application/json;charset=UTF-8")
	public @ResponseBody
	String invokeJsonp(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return "function() {return " + escape(invokeJson(request, response)) + ";}";
	}
	private String escape(String value) {
		value = StringUtils.replace(value, "\\", "\\\\");
		value = StringUtils.replace(value, "\r", "\\r");
		value = StringUtils.replace(value, "\n", "\\n");
		value = StringUtils.replace(value, "\t", "\\t");
		value = StringUtils.replace(value, "\"", "\\\"");
		return value;
	}

}
